package com.asiainfo.cms.system.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.asiainfo.cms.common.config.CmsConfig;
import com.asiainfo.cms.common.constant.UserConstants;
import com.asiainfo.cms.common.result.Result;
import com.asiainfo.cms.common.util.SecurityUtils;
import com.asiainfo.cms.common.util.file.FileUploadUtils;
import com.asiainfo.cms.common.vo.LoginUser;
import com.asiainfo.cms.system.entity.SysUser;
import com.asiainfo.cms.system.service.ISysUserService;
import com.asiainfo.cms.system.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController {
    @Autowired
    private ISysUserService userService;

    /**
     * 个人信息
     */
    @GetMapping
    public Result profile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        JSONObject data = new JSONObject();
        data.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        data.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return Result.success(data);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public Result updateProfile(@RequestBody SysUserVO user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        user.setUserName(loginUser.getUsername());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Result.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(loginUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {
            return Result.ok();
        }
        return Result.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Result.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            return Result.ok();
        }
        return Result.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = FileUploadUtils.upload(CmsConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                JSONObject ajax = new JSONObject();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                return Result.success(ajax);
            }
        }
        return Result.error("上传图片异常，请联系管理员");
    }
}
